package org.spbsu.apco.common.utils;

import org.springframework.util.Assert;

import java.io.UnsupportedEncodingException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * User: mikpan
 * Date: 12/12/12
 * Time: 2:58 PM
 */
public class NetworkUtils {
    public static final String X_MAC_SRC = "X_MAC_SRC";
    public static final String X_EVENT = "X_EVENT";

    public static final String X_NULL_VALUE = "=NULL=";
    private static String macAddress;
    private static String hostname;

    public static String getLocalMACAddress() throws SocketException, UnsupportedEncodingException {
        if (macAddress == null)
            initializeMacAddress();
        return macAddress;
    }

    public static String getHostname() throws UnknownHostException {
        if (hostname == null)
            initializeHostname();
        return hostname;
    }

    private static void initializeMacAddress() throws SocketException {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        NetworkInterface localInterface = interfaces.nextElement();
        Assert.notNull(localInterface, "No local network interfaces.");
        while (interfaces.hasMoreElements() && (localInterface.isVirtual() || localInterface.getHardwareAddress() == null || localInterface.getHardwareAddress().length == 0)) {
            localInterface = interfaces.nextElement();
        }
//        Assert.isTrue(localInterface.getHardwareAddress().length > 0, "MAC address cannot be determined.");
        macAddress = localInterface.getHardwareAddress() != null && localInterface.getHardwareAddress().length > 0 ? bytesToHex(localInterface.getHardwareAddress()) : "00-00-00-00-00-00";
    }

    private static void initializeHostname() throws UnknownHostException {
        hostname = java.net.InetAddress.getLocalHost().getHostName();
    }

    private static String bytesToHex(byte[] bytes) {
        final char[] hexArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] hexChars = new char[bytes.length * 3 - 1];
        int v;
        for (int j = 0; j < bytes.length; j++) {
            v = bytes[j] & 0xFF;
            hexChars[j * 3] = hexArray[v >>> 4];
            hexChars[j * 3 + 1] = hexArray[v & 0x0F];
            if (j * 3 + 3 < bytes.length * 3) {
                hexChars[j * 3 + 2] = '-';
            }
        }
        return new String(hexChars);
    }
}
